// 实现这个项目的构建任务
const { src, dest, parallel, series, watch } = require('gulp')
const del = require('del')
const browserSync = require('browser-sync')
const loadPlugins = require('gulp-load-plugins')
const plugins = loadPlugins()
const bs = browserSync.create()

// clean任务
const clean = () => {
  return del(['dist', 'temp'])
}

// 样式文件任务
const style = () => {
  return src('src/assets/styles/*.scss', { base: 'src' })
    .pipe(plugins.sass())
    .pipe(dest('temp'))
}

// js文件
const script = () => {
  return src('src/assets/scripts/*.js', { base: 'src' })
    .pipe(plugins.babel())
    .pipe(dest('temp'))
}

// html文件
const page = () => {
  return src('src/*.html', { base: 'src' })
    .pipe(plugins.swig({ caches: false }))
    .pipe(dest('temp'))
}

// 图片文件
const image = () => {
  return src('src/assets/images/**', { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

// 字体文件
const font = () => {
  return src('src/assets/fonts/**', { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

// 剩余文件
const extra = () => {
  return src('public/**', { base: 'public' })
    .pipe(dest('dist'))
}

// 处理html文件引用的第三方模块文件
const useref = () => {
  return src('temp/*.html', { base: 'temp' })
    .pipe(plugins.useref({ searchPath: ['temp', '.'] }))
    // 匹配不同文件，进行压缩
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(plugins.if(/\.html$/, plugins.htmlmin(
      {
        collapseWhitespace: true,
        minifyJS: true,
        minifyCSS: true,
        removeComments: true,
      }
    )))
    .pipe(dest('dist'))
}

// 开发模式
const serve = () => {
  // 监听各种文件修改，触发构建流程，从而触发热更新
  watch('src/assets/styles/*.scss', style)
  watch('src/assets/scripts/*.js', script)
  watch('src/*.html', page)
  watch([
    'src/assets/images/**',
    'src/assets/fonts/**',
    'public/**',
  ], bs.reload)

  bs.init({
    files: 'temp/**', // 服务器监听的资源文件
    server: {
      baseDir: ['temp', 'src', 'public'], // 服务器指向的资源文件
      routes: {
        '/node_modules': 'node_modules'
      }
    }
  })
}

// 合并任务
const compile = parallel(style, script, page)

// 上线前打包任务命令
const build = series(
  clean,
  parallel(
    series(compile, useref),
    image,
    font,
    extra
  )
)

// 开发命令
const dev = series(compile, serve)

module.exports = {
  clean,
  build,
  dev
}
